<template>
	<view class="login">
		<image src="@/static/images/public/logo.jpg" mode="scaleToFill"></image>
		<view class="name">运车网</view>
		<button class="btn"  open-type="getPhoneNumber" @getphonenumber="getPhoneNumberHandler">授权登录</button>
	</view>
</template>

<script>
	import Login from '@/api/login.js'
	import { setToken } from '@/utils/auth'
	export default {
		data() {
			return {
				userInfo: {
					encryptedData: '',
					iv: ''
				},
			}
		},
		onLoad() {
			// #ifdef MP-TOUTIAO  
			tt.login({
				success: function(res) {
					if (res.code) {} else {
						console.log('登录失败！' + res.errMsg);
					}
				},
				fail: function(err) {
					console.error('登录调用失败：', err);
				}
			});
			tt.getUserProfile({
				success: (res) => {
					console.log(res)
				},
				fail: (err) => {
					console.log(err)
				}
			});
			// #endif
		},
		methods: {
			getPhoneNumberHandler(e) {
				console.log(e)
				if (this.userInfo.iv !== '') {
					this.checkCars()
				} else if (e.detail.errMsg === 'getPhoneNumber:ok') {
					this.userInfo.encryptedData = e.detail.encryptedData
					this.userInfo.iv = e.detail.iv
					this.checkCars(e)
				} else if (e.detail.errMsg === 'no phone number') {
					uni.showToast({
						icon: 'none',
						title: '获取失败，请先去绑定手机号！'
					})
				}
			},
			async checkCars(e) {
				const res = await uni.login();
				let params = res;
				if(Array.isArray(res)) {
					params = res[1];
				}
				const data = {
					encryptedData: this.userInfo.encryptedData,
					iv: this.userInfo.iv,
					dyCode: params.code,
					kzplatform: '抖音平台'
				}
				const res2 = await Login.loginDefault(data);
				console.log(res2)
				if (res2.code == 200) {
					setToken(res2.token);
					uni.setStorageSync('userName', res2.sub);
					uni.setStorageSync('userProfile', res2.avatar);
					// 用户角色
					uni.setStorageSync('isCarrier', res2.isCarrier);
					if(res2.isCarrier != 0) {
						uni.setStorageSync('companyName', res2.companyName);
					}
					uni.switchTab({
						url: '/pages/userCenter'
					})
				} else {
					uni.showModal({
						title: '提示',
						content: '服务器错误！',
						showCancel: false,
						success: res => {
							console.log('确定')
						}
					})
				}
			}
		}
	}
</script>

<style scoped lang="less">
.login {
	width: 100%;
	height: 100%;
	background: #fff;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	.btn {
		border: 2rpx solid #022fa6;
		border-radius: 12rpx;
		background: #fff;
		color: #022fa6;
		width: 80vw;
		height: 80rpx;
		line-height: 80rpx;
		font-size: 32rpx;
		font-weight: 600;
		text-align: center;
	}
	.name {
		font-size: 36rpx;
		margin-bottom: 100rpx;
		color: #1a1a1a;
		font-weight: bold;
	}
	image {
		width: 160rpx;
		height: 160rpx;
		border-radius: 80rpx;
		margin-bottom: 20rpx;
		background: #999;
	}
}
</style>